package com.jjty.dataGenerator.jshjy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjty.dataGenerator.jserji.entity.ApiResponse;
import com.jjty.dataGenerator.jshjy.entity.JsHeartbeatData;
import com.jjty.dataGenerator.jshjy.mapper.JsHeartbeatDataMapper;
import com.jjty.dataGenerator.jshjy.utils.PushHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Slf4j
public class HeartbeatPushService {

    @Autowired
    private JsHeartbeatDataMapper heartbeatDataMapper;
    @Autowired
    private PushHttpClient pushHttpClient;
    @Value("${jsedu.channel}")
    private String channel;

    /**
     * 批量推送心跳数据（按未推送状态筛选）
     * @param limit 批量推送数量
     * @return 推送结果统计
     */
    public String pushBatchHeartbeat(int limit) {
        // 查询未推送的数据（状态为0）
        QueryWrapper<JsHeartbeatData> query = new QueryWrapper<>();
        query.eq("push_status", 0)
                .last("LIMIT " + limit); // 限制批量数量
        List<JsHeartbeatData> dataList = heartbeatDataMapper.selectList(query);

        if (dataList.isEmpty()) {
            return "无待推送的心跳数据";
        }

        int successCount = 0;
        int totalCount = dataList.size();

        // 逐条推送并更新状态
        for (JsHeartbeatData data : dataList) {
            // 转换为接口请求体（严格匹配文档字段）
            JsHeartbeatData request = new JsHeartbeatData();
            request.setChannel(channel);
            request.setImeiNo(data.getImeiNo());
            request.setLastHeartbeatTime(data.getLastHeartbeatTime());

            // 调用推送接口
            ApiResponse response = pushHttpClient.push(
                    "/openapi/stu-card/sync/heartbeat",
                    request
            );

            // 更新推送状态
            data.setPushTime(LocalDateTime.now());
            if (response.getCode() == 0) {
                data.setPushStatus(1); // 推送成功
                data.setPushMsg("推送成功");
                successCount++;
            } else {
                data.setPushStatus(2); // 推送失败
                data.setPushMsg("失败原因：" + response.getMsg());
            }
            heartbeatDataMapper.updateById(data);
        }

        return String.format("心跳数据批量推送完成，总条数：%d，成功：%d，失败：%d",
                totalCount, successCount, totalCount - successCount);
    }
}